package com.xingshang.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.xingshang.mapper.OrderMapper;
import com.xingshang.model.dto.CartItem;
import com.xingshang.model.po.*;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.xingshang.mapper.GoodsMapper;
import com.xingshang.service.*;

import com.xingshang.util.AlipayService;
import jakarta.servlet.http.HttpSession;
import lombok.RequiredArgsConstructor;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {


    private final AddressService addressService;
    private final AlipayService alipayService;
    private final CartService cartService;
    private final OrderItemService orderItemService;
    private final GoodsService goodsService;
    private final OrderMapper orderMapper;
    private final InvoiceService invoiceService;


    @Override
    public Order submitOrder(Integer userId, Integer addressId, String telphone, Integer payType, HttpSession session, String invoiceType, String title, String taxId, String bankCard) {
        System.out.println("提交订单service");
        //根据用户id进行多表联查
        List<CartItem> cartItems = cartService.selectByUserId(userId);
//        System.out.println("cartItems:"+cartItems);
        if (cartItems == null || cartItems.isEmpty()) {
            return null;
        }
        Address address = addressService.getById(addressId);

        if (address == null) {
            return null;
        }
        //订单编号
        String orderNo = "WN" + System.currentTimeMillis() + userId;

        BigDecimal totalMoney = getBigDecimal(cartItems);

        Order order = Order.builder().no(orderNo)
                .addTime(LocalDateTime.now())
                .userId(userId)
                .totalMoney(totalMoney)
                .address(address.getProvince() + address.getCity() + address.getArea() + address.getStreet())
                .accept(address.getAccept())
                .telphone(address.getTelphone())
                .payType(payType)
                .status("1")// 未支付
                .build();
        save(order);
        List<OrderItem> orderItems = new ArrayList<OrderItem>();
        cartItems.forEach(cartItem -> {
            orderItems.add(OrderItem.builder()
                    .orderId(order.getId())
                    .goodsId(cartItem.getGoodsId())
                    .name(cartItem.getGoodname())
                    .image(cartItem.getGoodimage())
                    .price(cartItem.getGoodprice())
                    .num(cartItem.getQuantity())
                    .build());
        });
        int i = orderItemService.batchInsert(orderItems);
        if (invoiceType != null && !invoiceType.equals("1")) { // 不是“不开发票”
            Invoice invoice = new Invoice();
            invoice.setOrderId(order.getId());
            invoice.setTitle(title);
            invoice.setOrderInfo("订单ID：" + order.getId());
            invoice.setType(invoiceType);
            if ("2".equals(invoiceType.toString()) || "3".equals(invoiceType.toString())) {
                invoice.setTaxId(taxId);
                invoice.setBankCard(bankCard);
            }
            invoice.setAddTime(LocalDateTime.now());

            invoiceService.addInvoice(invoice);
        }
        return order;

    }

    @NotNull
    private static BigDecimal getBigDecimal(List<CartItem> cartItems) {
        BigDecimal totalMoney = new BigDecimal("0");
        for (CartItem cartItem : cartItems) {
            System.out.println(cartItem.getGoodprice());
            BigDecimal salePrice = cartItem.getGoodprice() == null ? BigDecimal.ZERO : cartItem.getGoodprice();
            totalMoney = totalMoney.add(salePrice.multiply(new BigDecimal(cartItem.getQuantity())));

        }
        return totalMoney;
    }

    //让支付宝处理
    @Transactional
    @Override
    public String payOrder(Integer userId, String orderNo, HttpSession session, String orderId) {
        //1.购物车里是否有数据
        List<CartItem> cartItems = cartService.selectByUserId(userId);
        if (cartItems == null || cartItems.isEmpty()) {
            return null;
        }
        //2.判断库存
        for (CartItem item : cartItems) {
            //判断库存
            Goods good = goodsService.lambdaQuery().eq(Goods::getId, item.getGoodsId()).one();
            if (item.getQuantity() > good.getStock()) {
                return "fail:stock";
            }
        }
        //获取支付金额
        BigDecimal totalMoney = getBigDecimal(cartItems);
        //接入支付宝：
        String form = alipayService.createPayment(orderNo, "" + totalMoney, "支付订单号:" + orderNo);
        //保存订单id
        session.setAttribute("orderNo", orderNo);
        session.setAttribute("orderId", orderId);
        return form;
    }

    @Override
    public String orderSuccess(String orderNo, Integer userId, String orderId) {
        //支付成功后继续处理
        //获取购物车数据
        List<CartItem> cartItems = cartService.selectByUserId(userId);
        //3. 修改商品库存
        List<Goods> goodsList = new ArrayList<>();
        for (CartItem item : cartItems) {
            Goods one = goodsService.lambdaQuery().eq(Goods::getId, item.getGoodsId()).gt(Goods::getStock, item.getQuantity()).one();
            if (one != null) {
                one.setStock(one.getStock() - item.getQuantity());
                goodsList.add(one);
            }
        }
        goodsService.updateBatchById(goodsList);
        //清理购物车
        cartService.clearCart(userId, Integer.valueOf(orderId));
        // 更新订单状态
        this.updateOrderStatus(orderNo, "3", new Date());
        return "success";
    }

    private void updateOrderStatus(String orderNo, String status, Date date) {
        System.out.println("更新订单状态");
        System.out.println("订单号: " + orderNo);
        System.out.println("状态: " + status);
        System.out.println("时间: " + date);
        boolean b = orderMapper.updateOrderStatus(orderNo, status, date);
        if (b) {
            System.out.println("更新成功");
        } else {
            System.out.println("更新失败");
        }
    }


}
